package Client;

import java.io.*;
import java.net.*;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import Data.*;
import DataControl.ClientDataSender;
import DataControl.IClientDataSender;
import DataControl.IServerDataResolver;
import DataControl.ServerDataResolver;

public class client {
    public String serverIp = "cn-sz-yd-plustmp2.natfrp.cloud";
    public int serverPort = 10620;
    public Socket socket = null;
    private String SavePath=null;//下载的文件的保存的路径
    public ObjectInputStream inputStream;//接收的流
    public IClientDataSender clientDataSender = new ClientDataSender(socket,"123456");//创建一个发送的工厂
    public IServerDataResolver serverDataResolver = new ServerDataResolver();//创建一个接收的工厂



    public client(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    /**
     * 获取服务器返回的数据
     * @return
     */
    private void GetServerData() {
        try {
            inputStream = new ObjectInputStream(socket.getInputStream());
            System.out.println("获取服务器返回的数据中...");
            DataPort serverData = (DataPort) inputStream.readObject();
            //通过接收工厂来获取需要显示的数据或下载的数据
            serverDataResolver.setServerData(serverData);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行命令对应的客户端动作
     * @param Command
     */
    public void Do(String Command) {
        clientDataSender.setSocket(socket);
        System.out.println("客户端：更新客户端数据发送器的socket");
        clientDataSender.Send(Command);//发送命令
        System.out.println("客户端：发送客户端数据");
        GetServerData();//获取服务器返回的数据
        System.out.println("客户端：获取服务器返回的数据");
        ClinetData clinetData = clientDataSender.getClientData();
        serverDataResolver.Do(clinetData);//执行命令对应的客户端动作
    }

    /**
     * 客户端连接服务器
     */
    public void Connect() {
        try {
            socket = new Socket(serverIp, serverPort);
            System.out.println("连接服务器成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void Close() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        client client = new client("cn-sz-yd-plustmp2.natfrp.cloud",10620);
        client.Connect();
        while(true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入一个命令: ");
            String inputString = scanner.nextLine();
            System.out.println("客户端获取到命令："+inputString);
            if (inputString.equals("wq")){
                scanner.close();
                client.Close();
                break;
            }
            client.Do(inputString);//执行命令对应的客户端动作
        }
    }
}
